using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using ShoppingCenter.Backend.Api.Db;
using ShoppingCenter.Backend.Api.Model;
using ShoppingCenter.Backend.Api.Params;
using ShoppingCenter.Backend.Api.Repository;
using ShoppingCenter.Backend.Api.Utils;

namespace ShoppingCenter.Backend.Api.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]")]

    //商品控制器
    public class MerchandiseController : ControllerBase
    {
        private IConfiguration _configuration;

        //商品
        private IRepository<Merchandise> _merchandiseRepository;

        //规格
        private IRepository<Specifications> _specificationsRepository;

        // 商家
        private IRepository<Merchant> _merchantRepository;

        // 分类
        private IRepository<Commodity_category> _commodity_categoryRepository;

        // 商品详情
        private IRepository<Details> _detailsRepository;

        //属性
        private IRepository<Model.Attribute> _attributeRepository;
        //属性值
        private IRepository<Attribute_value> _attributeValueRepository;

        public MerchandiseController(IConfiguration configuration, IRepository<Model.Attribute> attributeRepository, IRepository<Attribute_value> attributeValueRepository, IRepository<Merchant> merchantRepository, IRepository<Commodity_category> commodity_categoryRepository, IRepository<Specifications> specificationsRepository, IRepository<Details> detailsRepository, IRepository<Merchandise> merchandiseRepository)
        {
            _configuration = configuration;
            _detailsRepository = detailsRepository;
            _merchantRepository = merchantRepository;
            _commodity_categoryRepository = commodity_categoryRepository;
            _merchandiseRepository = merchandiseRepository;
            _specificationsRepository = specificationsRepository;
            _attributeRepository = attributeRepository;
            _attributeValueRepository = attributeValueRepository;
        }

        //获取所有商品
        public dynamic Get()
        {
            //规格
            var specifications = _specificationsRepository.Table.ToList();

            //商品详情
            var detailsRepository = _detailsRepository.Table.ToList();

            var currentPage = int.Parse(Request.Query["currentPage"][0]);
            var pageSize = int.Parse(Request.Query["pageSize"][0]);

            // 分页
            var merchandise = _merchandiseRepository.Table.ToList().Skip((currentPage - 1) * pageSize).Take(pageSize); ;

            return new
            {
                Code = 1000,
                Data = new
                {
                    Data = merchandise,
                    Pager = new { currentPage, pageSize, totalSize = merchandise.Count() }
                },
                Msg = "获取所有商品成功"
            };
        }

        //商品模糊查询
        [HttpPost, Route("queryMerchandise")]
        public dynamic GetQuery(QueryData queryMerchandise)
        {

            var querydata = queryMerchandise.data;


            var merchandise = _merchandiseRepository.Table.Where(x => x.Name.Contains(querydata));
            var commodityCategory = _commodity_categoryRepository.Table.Where(x => x.Name == querydata).FirstOrDefault();

            if (querydata == null || querydata == "")
            {
                return new
                {
                    Code = 1000,
                    Data = merchandise,
                    Msg = "查询成功"
                };
            }

            // 优先查询分类
            if (commodityCategory != null)
            {

                //获取当前分类下的所有商品
                var merchandises = _merchandiseRepository.Table.Where(x => x.Commodity_categoryId == commodityCategory.Id).ToList();

                return new
                {
                    Code = 1000,
                    Data = merchandises,
                    Msg = "查询成功"
                };
            }


            if (merchandise != null)
            {
                return new
                {
                    Code = 1000,
                    Data = merchandise,
                    Msg = "查询成功"
                };
            }

            var res = new
            {
                Code = 104,
                Data = "",
                Msg = "没有你要找的数据"
            };

            //将结果实例化后输出
            return res;
        }


        //添加
        [HttpPost]
        public dynamic Post(CUR_Merchandise newMerchandise)
        {
            // 商品名、商品类别id、商家id、商品详情不可为空
            var MerchandiseName = newMerchandise.Name.Trim();

            //当前规格的属性和属性值不能为空必须初始化至少一个属性和值（这里只能初始化一个属性），库存和价格也不能为空
            if (string.IsNullOrEmpty(newMerchandise.Attribute) || string.IsNullOrEmpty(newMerchandise.Attribute_value) || newMerchandise.Inventory <= 0 || newMerchandise.Price <= 0)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "当前规格的属性和属性值不能为空,库存和价格都必须大于0"
                };
            }

            //获取分类和商家
            var CommodityCategory = _commodity_categoryRepository.Table.Where(x => x.Id == newMerchandise.Commodity_categoryId).FirstOrDefault();
            var Merchant = _merchantRepository.Table.Where(x => x.Id == newMerchandise.MerchantId).FirstOrDefault();

            if (string.IsNullOrEmpty(MerchandiseName) || CommodityCategory == null || Merchant == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = "商品名、商品类别id、商家id无效"
                };
            }

            //将商品详情添加到详情表
            var details = new Details
            {
                Word = newMerchandise.Word,
                Image = newMerchandise.Image
            };

            _detailsRepository.Insert(details);

            //获取查询到的商品详情id(获取最后一条详情的id)
            var detailsId = _detailsRepository.Table
            .Where(x => x.Word == newMerchandise.Word && x.Image == newMerchandise.Image)
            .ToList()
            .LastOrDefault().Id;


            //将商品的属性插入商品表中
            var merchandise = new Merchandise
            {
                Name = MerchandiseName,
                Commodity_categoryId = CommodityCategory.Id,
                MerchantId = Merchant.Id,
                DetailsId = detailsId,
                Msg = newMerchandise.Msg
            };

            _merchandiseRepository.Insert(merchandise);

            // 获取当前的属性和属性值
            var attribute = _attributeRepository.Table.Where(x => x.Name == newMerchandise.Attribute).FirstOrDefault();
            var attributeValue = _attributeValueRepository.Table.Where(x => x.Name == newMerchandise.Attribute_value).FirstOrDefault();

            //获取最后插入的商品id(获取最后一条商品的id)
            var merchandiseId = _merchandiseRepository.Table
            .Where(x => x.Name == MerchandiseName)
            .ToList()
            .LastOrDefault().Id;


            //如果属性和属性值都为空
            if (attribute == null && attributeValue == null)
            {
                //将属性添加到对应的表中
                var att = new Model.Attribute
                {
                    Name = newMerchandise.Attribute
                };

                //将属性值添加到对应的表中
                var attValue = new Attribute_value
                {
                    Name = newMerchandise.Attribute_value
                };

                _attributeRepository.Insert(att);
                _attributeValueRepository.Insert(attValue);

                // 获取刚刚插入的属性id
                var attributeId = _attributeRepository.Table
                .Where(x => x.Name == newMerchandise.Attribute)
                .ToList()
                .LastOrDefault().Id;

                //获取刚刚插入的属性值id
                var attributeValueId = _attributeValueRepository.Table
                .Where(x => x.Name == newMerchandise.Attribute_value)
                .ToList()
                .LastOrDefault().Id;

                // 插入规格表
                var spec001 = new Specifications
                {
                    AttributeId = attributeId,
                    Attribute_valueId = attributeValueId,
                    MerchandiseId = merchandiseId,
                    Inventory = newMerchandise.Inventory,
                    Price = newMerchandise.Price
                };

                _specificationsRepository.Insert(spec001);

                return new
                {
                    Code = 1000,
                    Data = spec001,
                    Msg = "添加商品成功"
                };


            }

            if (attribute == null)
            {
                //将属性添加到对应的表中
                var att = new Model.Attribute
                {
                    Name = newMerchandise.Attribute
                };

                _attributeRepository.Insert(att);

                // 获取刚刚插入的属性id
                var attributeId = _attributeRepository.Table
                .Where(x => x.Name == newMerchandise.Attribute)
                .ToList()
                .LastOrDefault().Id;

                // 插入规格表
                var spec001 = new Specifications
                {
                    AttributeId = attributeId,
                    Attribute_valueId = attributeValue.Id,
                    MerchandiseId = merchandiseId,
                    Inventory = newMerchandise.Inventory,
                    Price = newMerchandise.Price
                };

                _specificationsRepository.Insert(spec001);

                return new
                {
                    Code = 1000,
                    Data = spec001,
                    Msg = "添加商品成功"
                };

            }

            if (attributeValue == null)
            {
                //将属性值添加到对应的表中
                var attValue = new Attribute_value
                {
                    Name = newMerchandise.Attribute_value
                };

                _attributeValueRepository.Insert(attValue);

                //获取刚刚插入的属性值id
                var attributeValueId = _attributeValueRepository.Table
                .Where(x => x.Name == newMerchandise.Attribute_value)
                .ToList()
                .LastOrDefault().Id;

                // 插入规格表
                var spec001 = new Specifications
                {
                    AttributeId = attribute.Id,
                    Attribute_valueId = attributeValueId,
                    MerchandiseId = merchandiseId,
                    Inventory = newMerchandise.Inventory,
                    Price = newMerchandise.Price
                };

                _specificationsRepository.Insert(spec001);

                return new
                {
                    Code = 1000,
                    Data = spec001,
                    Msg = "添加商品成功"
                };
            }


            // 如果属性和属性值原本表里就有不用重复添加属性和属性值
            // 将规格属性插入规格表
            var specification = new Specifications
            {
                AttributeId = attribute.Id,
                Attribute_valueId = attributeValue.Id,
                MerchandiseId = merchandiseId,
                Inventory = newMerchandise.Inventory,
                Price = newMerchandise.Price
            };

            _specificationsRepository.Insert(specification);

            return new
            {
                Code = 1000,
                Data = specification,
                Msg = "添加商品成功"
            };

            //将结果实例化后输出
        }

        //根据id修改商品信息
        // [HttpPut("{id}")]
        // public dynamic Put(int id, CUR_Merchandise updateMerchandise)
        // {
        //     var MerchandiseName = updateMerchandise.Name.Trim();
        //     var CommodityCategoryId=updateMerchandise.Commodity_categoryId;
        //     var DetailsId=updateMerchandise.DetailsId;
        //     var Msg=updateMerchandise.Msg;

        //     if (string.IsNullOrEmpty(MerchandiseName) || CommodityCategoryId>0|| DetailsId>0)
        //     {
        //         return new
        //         {
        //             Code = 104,
        //             Data = "",
        //             Msg = ""
        //         };
        //     }


        //     //通过Id获取要修改的管理员
        //     var adminUpdate = _adminRepository.GetById(id);

        //     if (adminUpdate == null)
        //     {
        //         return new
        //         {
        //             Code = 104,
        //             Data = "",
        //             Msg = "你要更新的管理员不存在"
        //         };
        //     }

        //     var u = _usersRepository.Table.Where(x => x.Name == username).ToList().FirstOrDefault();
        //     var admin = _adminRepository.Table.Where(x => x.Name == username).ToList().FirstOrDefault();

        //     if (u != null || (admin!=null && admin.Id!=id))
        //     {
        //         return new
        //         {
        //             Code = 104,
        //             Data = "",
        //             Msg = "当前用户名已存在,请换个用户名后重试"
        //         };
        //     }

        //     //将要修改的账号密码重新赋给Admin
        //     adminUpdate.Name = username;
        //     adminUpdate.Password = password;
        //     adminUpdate.Remarks = updateAdmin.Remarks;

        //     return new
        //     {
        //         Code = 1000,
        //         Data = adminUpdate,
        //         Msg = "更新数据成功"
        //     };

        //     // return JsonHelper.Serialize(res);

        // }

        //根据id删除商品



        [HttpDelete("{id}")]
        public dynamic Dalete(int id)
        {

            var user = _merchandiseRepository.GetById(id);

            if (user == null)
            {
                return new
                {
                    Code = 104,
                    Data = "",
                    Msg = string.Format("无法删除id为{0}的商品", id)
                };
            }

            _merchandiseRepository.Delete(id);

            return new
            {
                Code = 1000,
                Data = "",
                Msg = string.Format("删除id为{0}的商品成功", id)
            };
        }
    }
}